import time
import threading
import os

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, 
                             QFrame)
from PyQt5.QtGui import QFont, QTextCursor, QColor, QIcon, QTextCharFormat
from PyQt5.QtCore import Qt, QTimer

from meet_record.ui_components import IconButton
from meet_record.summary_dialog import SummaryDialog
from meet_record.api import SummaryAPI

# 会议记录显示主控件
class MeetingRecordViewer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 初始化录音状态
        self.is_recording = False
        
        self.last_line_started = False  # 标记是否已经开始了新行
        self.manual_scrolled = False   # 标记用户是否手动滚动了会议记录
        self.scroll_timer = QTimer()    # 用于检测是否停止滚动的计时器
        
        self.init_ui()
        self.setup_signals()
        
        # # 初始化会议记录内容
        # self.add_record("会议记录已开启", new_line=True)
    
    def init_ui(self):
        """初始化UI界面"""
        self.setStyleSheet("background-color: transparent;")
        
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)
        
        # 会议记录显示容器
        record_container = QFrame()
        record_container.setStyleSheet("""
            QFrame {
                background-color: #FFFFFF;
                border-radius: 8px;
                border: 1px solid #E0E0E0;
            }
        """)
        record_layout = QVBoxLayout(record_container)
        record_layout.setContentsMargins(0, 0, 0, 0)
        
        self.record_area = QTextEdit()
        self.record_area.setReadOnly(True)
        self.record_area.setStyleSheet("""
            QTextEdit {
                background-color: #FFFFFF;
                border: none;
                border-radius: 8px;
                font-family: Consolas, 'Courier New', monospace;
                font-size: 13px;
                color: #333333;
                padding: 10px;
            }
        """)
        
        # 配置滚动条样式
        self.record_area.verticalScrollBar().setStyleSheet("""
            QScrollBar:vertical {
                background: transparent;
                width: 8px;
            }
            QScrollBar::handle:vertical {
                background: #BDBDBD;
                min-height: 20px;
                border-radius: 4px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """)
        
        record_layout.addWidget(self.record_area)
        main_layout.addWidget(record_container, 1)
        
        # 控制面板
        self.control_panel = QWidget()
        self.control_panel.setStyleSheet("background-color: transparent;")
        control_layout = QHBoxLayout(self.control_panel)
        control_layout.setSpacing(10)
        control_layout.setContentsMargins(5, 5, 5, 5)
        control_layout.setAlignment(Qt.AlignRight)
        
        # 控制按钮
        icons_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
        self.scroll_btn = IconButton(
            os.path.join(icons_dir, "scroll.svg"),
            "滚动到底部"
        )
        self.scroll_btn.clicked.connect(self.scroll_to_bottom)
        
        self.export_btn = IconButton(
            os.path.join(icons_dir, "export.svg"),
            "导出为TXT"
        )
        self.export_btn.clicked.connect(self.export_text)
        
        self.clear_btn = IconButton(
            os.path.join(icons_dir, "clear.svg"),
            "清空会议记录"
        )
        self.clear_btn.clicked.connect(self.clear_content)
        
        self.summary_btn = IconButton(
            os.path.join(icons_dir, "summary.svg"),
            "总结会议记录"
        )
        self.summary_btn.clicked.connect(self.summarize_text)
        
        # 添加录音按钮
        self.record_btn = IconButton(
            os.path.join(icons_dir, "mic.svg"),
            "录音开关"
        )
        self.record_btn.clicked.connect(self.toggle_recording)
        
        # 左侧控制区域（录音按钮）
        left_control = QWidget()
        left_control.setStyleSheet("background-color: transparent;")
        left_layout = QHBoxLayout(left_control)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.addWidget(self.record_btn)
        
        # 右侧控制区域（其他按钮）
        right_control = QWidget()
        right_control.setStyleSheet("background-color: transparent;")
        right_layout = QHBoxLayout(right_control)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(15)  # 增加按钮间距
        right_layout.addWidget(self.scroll_btn)
        right_layout.addWidget(self.export_btn)
        right_layout.addWidget(self.clear_btn)
        right_layout.addWidget(self.summary_btn)
        
        # 将左右两侧添加到主控制布局
        control_layout.addWidget(left_control, 1, Qt.AlignLeft)
        control_layout.addWidget(right_control, 0, Qt.AlignRight)
        
        # 添加一个边框，使控制面板更加明显
        self.control_panel.setStyleSheet("""
            background-color: transparent;
            padding: 5px;
        """)
        
        main_layout.addWidget(self.control_panel)
        self.setLayout(main_layout)
        
        # 创建总结对话框
        self.summary_dialog = SummaryDialog(self)
    
    def setup_signals(self):
        """设置信号连接"""
        # 连接会议记录区域的滚动事件
        self.record_area.verticalScrollBar().valueChanged.connect(self.handle_scroll)
        
        # 设置滚动检测计时器（2000ms）
        self.scroll_timer.setInterval(2000)
        self.scroll_timer.setSingleShot(True)
        self.scroll_timer.timeout.connect(self.reset_manual_scroll)
    
    def handle_scroll(self):
        """处理用户滚动事件"""
        scrollbar = self.record_area.verticalScrollBar()
        at_bottom = scrollbar.value() == scrollbar.maximum()
        
        if not at_bottom:
            self.manual_scrolled = True
            self.scroll_timer.start()
    
    def reset_manual_scroll(self):
        """重置手动滚动标志"""
        self.manual_scrolled = False
    
    def current_time(self):
        """获取当前格式化时间"""
        return time.strftime("%H:%M:%S")
    
    def startRecord(self):
        self.is_recording = True
        
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons", "mic_active.svg")
        self.record_btn.setIcon(QIcon(icon_path))
        self.record_btn.setToolTip("停止录音")
    
    def add_record(self, text, new_line=False):
        """
        添加会议记录到显示区域
        
        :param text: 要添加的会议记录文本
        :param new_line: 是否开启新行（带时间戳）
        """
        if not getattr(self, "is_recording", False):
             return
        cursor = self.record_area.textCursor()
        cursor.movePosition(QTextCursor.End)
        
        # 如果需要新行或还没有开始行
        if new_line:
            # 添加换行符（如果已经有内容）
            if self.last_line_started:
                cursor.insertText("\n")
            
            # 添加时间戳
            timestamp = f"[{self.current_time()}] "
            cursor.insertText(timestamp)
            
            # 设置时间戳颜色
            format = QTextCharFormat()
            format.setForeground(QColor("#1976D2"))  # 深蓝色
            format.setFontWeight(QFont.Bold)
            cursor.setCharFormat(format)
            
            self.last_line_started = True
        else:
            # 如果不是新行，确保内容直接追加
            cursor.insertText("")
        
        # 添加会议记录内容
        content_format = QTextCharFormat()
        content_format.setForeground(QColor("#333333"))
        cursor.setCharFormat(content_format)
        cursor.insertText(text)
        
        # 如果用户没有手动滚动，自动滚动到底部
        scrollbar = self.record_area.verticalScrollBar()
        at_bottom = scrollbar.value() == scrollbar.maximum()
        
        if not self.manual_scrolled or at_bottom:
            self.scroll_to_bottom()
    
    def scroll_to_bottom(self):
        """滚动会议记录到底部"""
        scrollbar = self.record_area.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())
    
    def export_text(self):
        """导出会议记录为文本文件"""
        # 在实际应用中，这里需要实现导出文件功能
        print("Export function called")
        self.add_record("导出会议记录文件到 meeting_record_export.txt", new_line=True)
    
    def clear_content(self):
        """清空会议记录内容"""
        self.record_area.clear()
        self.last_line_started = False
        # self.add_record("会议记录已清空", new_line=True)
    
    def toggle_recording(self):
        """切换录音状态"""
        # 获取当前录音状态
        is_recording = getattr(self, "is_recording", False)
        
        # 切换状态
        is_recording = not is_recording
        self.is_recording = is_recording
        
        # 更新按钮图标和提示
        if is_recording:
            # 录音中图标 - 红色麦克风
            icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons", "mic_active.svg")
            self.record_btn.setIcon(QIcon(icon_path))
            self.record_btn.setToolTip("停止录音")
            # self.add_record("开始录音", new_line=True)
            
            # 设置语音助手为会议记录模式
            try:
                self.app_state.meeting_recording = True
                self.app_state.waiting_for_wake = False  # 保持唤醒状态
            except Exception as e:
                print(f"设置会议记录模式失败: {str(e)}")
        else:
            # 非录音图标 - 蓝色麦克风
            icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons", "mic.svg")
            self.record_btn.setIcon(QIcon(icon_path))
            self.record_btn.setToolTip("开始录音")
            # self.add_record("停止录音", new_line=True)
            
            # 退出会议记录模式 -- 仅变更状态，
            # try:
            #     self.app_state.meeting_recording = False
            #     self.app_state.waiting_for_wake = True  # 恢复等待唤醒状态
            # except Exception as e:
            #     print(f"退出会议记录模式失败: {str(e)}")
    
    def summarize_text(self):
        """总结会议记录内容"""
        self.is_recording = False
        self.summary_dialog.show_loading()
        self.summary_dialog.show()
        
        # 获取会议记录内容
        text_content = self.get_record_content()
        if not text_content.strip():
            self.summary_dialog.show_result.emit("## 无内容可总结\n\n当前会议记录为空，请先录制会议内容。")
            return
            
        # 在后台线程中生成总结
        threading.Thread(target=self.generate_summary, args=(text_content,), daemon=True).start()
    
    def get_record_content(self):
        """获取会议记录内容"""
        # 获取文本编辑器中的所有内容
        content = self.record_area.toPlainText()
        # 将行头的时间戳移除
        lines = content.split('\n')
        processed_lines = []
        for line in lines:
            # 移除形如 [HH:MM:SS] 的时间戳
            if line.startswith('[') and ']' in line:
                timestamp_end = line.find(']') + 1
                if timestamp_end < len(line):
                    processed_lines.append(line[timestamp_end:].strip())
                else:
                    processed_lines.append('')
            else:
                processed_lines.append(line)
        return '\n'.join(processed_lines)
    
    def generate_summary(self, text_content):
        """生成会议记录总结"""
        # 步骤1: 提交任务
        response = SummaryAPI.submit_task(text_content)
        
        # 检查response是否为None
        if response is None:
            self.summary_dialog.show_result.emit("## 总结任务提交失败\n\n无法连接到总结服务，请检查网络连接后再试。")
            return
            
        task_id = response.get("task_id")
        
        if not task_id:
            self.summary_dialog.show_result.emit("## 总结任务提交失败\n\n无法创建总结任务，请稍后再试。")
            return
        
        print(f"生成总结，任务ID: {task_id}")
        
        # 步骤2: 轮询任务状态
        max_attempts = 20  # 最大轮询次数
        polling_interval = 5  # 轮询间隔（秒）
        attempts = 0
        
        while attempts < max_attempts:
            attempts += 1
            time.sleep(polling_interval)
            
            # 获取任务状态
            result = SummaryAPI.get_task_result(task_id)
            progress = min(attempts * 5, 95)  # 进度估算
            
            # 更新UI进度
            self.summary_dialog.update_progress.emit(progress)
            
            if result["status"] == "completed":
                # 任务完成，显示结果
                summary_text = result.get("result", "总结生成成功，但内容为空")
                # 确保内容以Markdown格式显示，以便高亮
                if not summary_text.startswith("#"):
                    summary_text = f"## 会议总结\n\n{summary_text}"
                self.summary_dialog.show_result.emit(summary_text)
                return
            elif result["status"] == "failed":
                # 任务失败，使用Markdown格式以便高亮显示
                error_msg = result.get("error", "未知错误")
                formatted_error = f"## 总结生成失败\n\n**错误信息**：\n\n{error_msg}"
                self.summary_dialog.show_result.emit(formatted_error)
                return
        
        # 如果轮询超时
        self.summary_dialog.show_result.emit("## 总结生成超时\n\n会议记录分析未能及时完成，请稍后查看结果。")